<template>
  <div id="product-home">
    <nav class="top-navbar" :class="{ fixed: isSticky }">
      <div class="back">
        <button>&lt;</button>
      </div>
      <div class="nav-right">
        <a href="#" class="nav-link">首页</a>
        <a href="#" class="nav-link">个人中心</a>
        <a href="#" class="nav-link">购物车</a>
        <a href="#" class="nav-link">收藏夹</a>
        <a href="#" class="nav-link">帮助中心</a>
        <button class="sign-in-button">Sign in</button>
        <button class="register-button">Register</button>
      </div>
    </nav>

    <div class="search-category-container">
      <div class="search-box">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索商品..."
          @keyup.enter="filterProducts"
        />
        <button @click="filterProducts">搜索</button>
      </div>

      <div class="category-nav">
        <span class="category-title">商品分类：</span>
        <ul class="category-list">
          <li
            v-for="category in categories"
            :key="category.id"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            {{ category.name }}
          </li>
        </ul>
      </div>
    </div>

    <div class="product-list-container">
      <h2>商品列表</h2>
      <div class="product-list">
        <div
          class="product-item"
          v-for="(product, index) in filteredProducts"
          :key="index"
          @click="goToDetail(product.product_id)"
        >
          <img :src="product.image_url" alt="product" class="product-image" />
          <div class="product-info">
            <span class="product-name">{{ product.name }}</span>
            <span class="product-price">¥{{ product.price }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';

const isSticky = ref(false);
const products = ref([]);
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '食品' },
  { id: 2, name: '娱乐' },
  { id: 3, name: '物品' }
]);
const searchQuery = ref('');
const selectedCategory = ref(0);
const router = useRouter();

const loadData = async () => {
  try {
    const response = await fetch('/Carts.json');
    const data = await response.json();
    products.value = data.cart.items;
  } catch (error) {
    console.error('加载数据失败:', error);
  }
};

const filteredProducts = computed(() => {
  if (!products.value) {
    return [];
  }
  return products.value.filter(product => {
    const categoryName = categories.value.find(c => c.id === selectedCategory.value)?.name;
    const isMatchCategory = categoryName === '全部' || product.type === categoryName;
    const isMatchSearch = product.name.toLowerCase().includes(searchQuery.value.toLowerCase());
    return isMatchCategory && isMatchSearch;
  });
});

const goToDetail = (productId) => {
  router.push({ name: 'ProductDetail', params: { id: productId } });
};

const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId;
};

const filterProducts = () => {
  // 可以添加更多搜索逻辑
};

watch(selectedCategory, () => {
  searchQuery.value = '';
});

const handleScroll = () => {
  if (window.pageYOffset > 0) {
    isSticky.value = true;
  } else {
    isSticky.value = false;
  }
};

onMounted(() => {
  loadData();
  window.addEventListener('scroll', handleScroll);
});

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.search-category-container {
  padding: 20px;
  background: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.search-box button {
  padding: 8px 16px;
  background: #333;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.category-nav {
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-title {
  font-weight: bold;
}

.category-list {
  display: flex;
  gap: 20px;
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-list li {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-list li:hover {
  background: #f0f0f0;
}

.category-list li.active {
  background: #333;
  color: white;
}

* {
  /* margin: 0 auto; */
  padding: 0;
}

#app {
  width: 100vw;
  height: auto;
  margin: 0;
  padding-top: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

.product-list-container {
  padding: 20px;
  display: grid;
  justify-content: center;
  justify-items: center;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.product-item {
  width: 200px;
  border: 1px solid #ccc;
  padding: 10px;
  cursor: pointer;
  text-align: center;
}

.product-image {
  width: 80px;
  height: auto;
}

.product-info {
  margin-top: 10px;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
}

.product-price {
  color: #333;
}

.top-navbar {
  display: flex;
  justify-content: space-between;
  gap: 20vh;
  background-color: #f4f4f4;
  padding: 10px;
  position: relative;
  z-index: 100px;
  transition: all 0.3s ease;
}

.back {
  display: flex;
  justify-content: start;
}

.nav-right {
  display: flex;
  align-content: flex-end;
}

.nav-link:hover {
  color: white;
  background-color: #333;
  border-radius: 20%;
}

.fixed {
  position: sticky;
  top: 0;
  width: 100%;
  background-color: #f4f4f4;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.nav-link {
  margin-right: 20px;
  text-decoration: none;
  color: #333;
}

.sign-in-button,
.register-button,
.sign-out-button {
  background-color: #333;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}
</style>